package ink.xiaobaibai.controller.wxPay;

import ink.xiaobaibai.serviceOxy.pay.IPayService;
import ink.xiaobaibai.serviceOxy.pay.impl.PayServiceImpl;
import ink.xiaobaibai.util.RequestUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 支付接口
 * @author: 小白白
 * @create: 2021-05-20
 **/

@Api(tags = "支付接口")
@RequestMapping("/wx-pay")
@RestController
@Slf4j
public class PayController {

    @Autowired
    private IPayService payService;

    /**
     * 回调接口
     */
    @PostMapping("/callback")
    @ApiOperation("订单支付回调")
    @ApiIgnore
    public Map<String, String> payNotifyUrl(HttpServletRequest request, HttpServletResponse response) {
        PayServiceImpl.CallbackResult callbackResult = this.payService.decryptPayResponseObj(RequestUtil.readAsChars(request));
        if (callbackResult == null) {
            log.error("数据解密错误");
            return this.failMap("数据解密错误", response);
        }
        log.info(callbackResult.toString());
        try {
            boolean result = this.payService.handleCallback(callbackResult);
            if (!result) {
                return this.failMap("意料中的错误", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("严重错误:" + e.getMessage());
            return this.failMap("服务器内部错误", response);
        }
        log.info("成功一笔");
        return this.okMap();
    }

    private Map<String, String> okMap() {
        Map<String, String> resultMap = new HashMap<>(2);
        resultMap.put("code", "SUCCESS");
        resultMap.put("message", "成功接收");
        return resultMap;
    }

    private Map<String, String> failMap(String msg, HttpServletResponse response) {
        Map<String, String> resultMap = new HashMap<>(2);
        resultMap.put("code", "error");
        resultMap.put("message", msg);
        response.setStatus(500);
        return resultMap;
    }

}
